package com.sky.common.config;


import com.sky.common.utils.Threads;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * 定时任务配置
 *
 */
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }


    @Bean("scheduledExecutor")
    public ScheduledThreadPoolExecutor taskExecutor() {
        return new ScheduledThreadPoolExecutor(
                20,
                new BasicThreadFactory.Builder()
                        .namingPattern("schedule-pool-%d")
                        .daemon(false)
                        .build()) {

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                Threads.printException(r, t);
            }

            // 添加拒绝策略
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                if (getQueue().size() > 1000) {
                    throw new RejectedExecutionException("任务队列已满");
                }
                super.beforeExecute(t, r);
            }
        };
    }

}